<!DOCTYPE html>
<html lang="en">
<head>
	<#include "../static/top.ftl" >
    <link rel="stylesheet" href="/res/assets/css/bootstrap-datepicker.css">
    <link rel="stylesheet" href="/res/assets/css/jquery.webui-popover.min.css">
    <link rel="stylesheet" href="/res/assets/css/bootstrap-select.css">
    <link rel="stylesheet" href="../../res/libs/misc/datatables/datatables.min.css">
    <link rel="stylesheet" href="../../res/assets/css/bootstrap-table.css">
    <link rel="stylesheet" href="../../res/assets/css/jqcloud.css">
</head>

<body class="menubar-left menubar-unfold menubar-light theme-primary">
<!--============= start main area -->

<!-- APP NAVBAR ==========-->



<#include "../static/header.ftl" >

<!--========== END app navbar -->

<!-- APP ASIDE ==========-->


<#include "../static/menu.ftl" >
<!--========== END app aside -->
<!-- navbar search -->

<!-- APP MAIN ==========-->
<main id="app-main" class="app-main">
    <div class="wrap">
        <section class="app-content">
        <#--筛选框-->
            <div class="row">
                <div class="col-md-12">
                    <div class="widget">
                        <header class="widget-header">
                            <h4 class="widget-title">
                                <form class="form-inline" style="height:50px">
                                    <div class="col-md-7">
                                    <div class="form-group col-md-4">
                                        <label>起始时间</label>
                                        <div class="input-group date datepicker" id="start_datapicker"
                                             data-provide="datepicker"
                                             style="width: 69%;padding:0px">
                                            <input type="text" class="form-control" placeholder="时间" id="start_date"
                                                   style="min-width:70px;">
                                            <div class="input-group-addon">
                                                <span class="glyphicon glyphicon-th"></span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label>结束时间</label>
                                        <div class="input-group date datepicker" data-provide="datepicker"
                                             style="width: 69%;padding:0px">
                                            <input type="text" class="form-control" placeholder="时间" id="end_date"
                                                   style="min-width:70px;">
                                            <div class="input-group-addon">
                                                <span class="glyphicon glyphicon-th"></span>
                                            </div>
                                        </div>
                                    </div>
                                    </div>
                                </form>
                                <form class="form-inline" style="height:50px">
                                    <div class="col-md-7">
                                    <div class="form-group col-md-4">
                                        <label>城市&emsp;&emsp;</label>
                                        <select class="form-control" id="city_select" style="min-width:90px;width: 69%"
                                                title="">

                                        </select>
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label>&emsp;&emsp;品类</label>
                                        <select class="form-control" id="cate_select"
                                                style="min-width:90px;width: 69%">

                                        </select>
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label>&emsp;&emsp;品牌</label>
                                        <select class="form-control" id="brand_select"
                                                style="min-width:90px;width: 69%">

                                        </select>
                                    </div>
                                    </div>
                                    <div class="col-md-5" style="padding:0 0">
                                    <div class="form-group col-md-8" style="padding:0 0">
                                        <label style="padding-left: 30px">店铺</label>
                                        <select class="form-control selectpicker" id="shop_select"
                                                data-live-search="true" data-live-search-placeholder="搜索店铺..." style="min-width:150px;width: 80%">

                                        </select>
                                    </div>
                                    <div class="form-group col-md-2">
                                        <button type="button" class="btn rounded btn-default button_active" id="search">
                                            确认
                                        </button>
                                    </div>
                                    </div>
                                </form>
                            </h4>
                        </header>
                    </div>
                </div>
            </div>

        <#--店铺信息-->
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-success panel-custom"
                         style="border-bottom-color:  #ba1b20;border-top-color: #ba1b20;">
                        <div class="panel-body">
                            <div class="col-sm-2"></div>
                            <div class="col-sm-4">
                                <h3 style="text-align: center">店铺基本信息</h3>
                                <div id="shop_info"></div>
                            </div>
                            <div class="col-sm-5">
                                <div class="widget-body" id="mapDiv" style="height: 260px">

                                </div><!-- .widget-body -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <#--总览-->
            <div class="row">
                <div class="col-sm-12 col-md-12">
                    <div class="panel panel-success panel-custom"
                         style="border-bottom-color:  #ba1b20;border-top-color: #ba1b20;">
                        <div class="panel-body">
                            <div class="col-md-4 col-sm-6">
                                <div class="widget">
                                    <header class="widget-header">
                                        <h4 class="widget-title">销售额</h4>
                                    </header><!-- .widget-header -->
                                    <hr class="widget-separator">
                                    <div class="widget-body p-t-lg">
                                        <div class="row">
                                            <div class="col-sm-12 col-md-6" style="padding:0 0;width:80px;height:80px;">
                                                <div style="width:100%;height:100%;
                                                            border-radius:50%;background-color: #ffe6e9;">
                                                    <div style="width:60px;height:60px;
                                                            border-radius:50%;background-color: #ff7a8b;
                                                                margin: auto;position: absolute;top: 0; left: 0; bottom: 0; right: 0;">
                                                        <img style="width:50%;height:50%;background-color: #ff7a8b;margin: auto;position: absolute;top: 0; left: 0; bottom: 0; right: 0;" src="/res/assets/images/brand/销售额icon.png">
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="col-sm-12 col-md-8">
                                                <div class="clearfix m-b-md">
                                                    <h3 class="pull-left m-0 fw-500" style="color: #ba1b20">
                                                        <span class="counter" data-plugin="counterUp" id="sales">- </span>元
                                                    </h3>
                                                </div>
                                                <h4 id="sales_mom">环比增长：- % <i class="glyphicon glyphicon-arrow-up"
                                                                               style="color: #21dd21"></i></h4>
                                                <h4 id="sales_yoy">同比增长：- % <i class="glyphicon glyphicon-arrow-up"
                                                                     style="color: #21dd21"></i></h4>
                                            </div>
                                        </div>
                                    </div><!-- .widget-body -->
                                </div><!-- .widget -->
                            </div>
                            <div class="col-md-4 col-sm-6">
                                <div class="widget">
                                    <header class="widget-header">
                                        <h4 class="widget-title">客单数</h4>
                                    </header><!-- .widget-header -->
                                    <hr class="widget-separator">
                                    <div class="widget-body p-t-lg">
                                        <div class="row">
                                            <div class="col-sm-12 col-md-6" style="padding:0 0;width:80px;height:80px;">
                                                <div style="width:100%;height:100%;
                                                            border-radius:50%;background-color: #ffe6e9;">
                                                    <div style="width:60px;height:60px;
                                                            border-radius:50%;background-color: #ff7a8b;
                                                                margin: auto;position: absolute;top: 0; left: 0; bottom: 0; right: 0;">
                                                        <img style="width:50%;height:50%;background-color: #ff7a8b;margin: auto;position: absolute;top: 0; left: 0; bottom: 0; right: 0;" src="/res/assets/images/brand/客单.png">
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="col-sm-12 col-md-8">
                                                <div class="clearfix m-b-md">
                                                    <h3 class="pull-left m-0 fw-500" style="color: #ba1b20">
                                                        <span class="counter" data-plugin="counterUp" id="tc">- </span>笔
                                                    </h3>
                                                </div>
                                                <h4 id="tc_mom">环比增长：- % <i class="glyphicon glyphicon-arrow-up"
                                                                            style="color: #21dd21"></i></h4>
                                                <h4 id="tc_yoy">同比增长：- % <i class="glyphicon glyphicon-arrow-up"
                                                                            style="color: #21dd21"></i></h4>
                                            </div>
                                        </div>
                                    </div><!-- .widget-body -->
                                </div><!-- .widget -->
                            </div>
                            <div class="col-md-4 col-sm-6">
                                <div class="widget">
                                    <header class="widget-header">
                                        <h4 class="widget-title">客单价</h4>
                                    </header><!-- .widget-header -->
                                    <hr class="widget-separator">
                                    <div class="widget-body p-t-lg">
                                        <div class="row">
                                            <div class="col-sm-12 col-md-6" style="padding:0 0;width:80px;height:80px;">
                                                <div style="width:100%;height:100%;
                                                            border-radius:50%;background-color: #ffe6e9;">
                                                    <div style="width:60px;height:60px;
                                                            border-radius:50%;background-color: #ff7a8b;
                                                                margin: auto;position: absolute;top: 0; left: 0; bottom: 0; right: 0;">
                                                        <img style="width:50%;height:50%;background-color: #ff7a8b;margin: auto;position: absolute;top: 0; left: 0; bottom: 0; right: 0;" src="/res/assets/images/brand/平均.png">
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="col-sm-12 col-md-8">
                                                <div class="clearfix m-b-md">
                                                    <h3 class="pull-left m-0 fw-500" style="color: #ba1b20">
                                                        <span class="counter" data-plugin="counterUp"
                                                              id="ta">- </span>元
                                                    </h3>
                                                </div>
                                                <h4 id="ta_mom">环比增长：- % <i class="glyphicon glyphicon-arrow-up"
                                                                            style="color: #21dd21"></i></h4>
                                                <h4 id="ta_yoy">同比增长：- % <i class="glyphicon glyphicon-arrow-up"
                                                                            style="color: #21dd21"></i></h4>
                                            </div>
                                        </div>
                                    </div><!-- .widget-body -->
                                </div><!-- .widget -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <#--竞争店铺总览-->
            <div class="row" id="table_shop">
                <div class="col-md-12"">
                <div class="widget">
                    <div class="widget-body" style="text-align: center;">
                    <table id="shopTable" data-plugin="DataTable"
                           class="table table-striped"
                           cellspacing="0" width="90%">
                        <thead>
                        <tr role="row">
                            <th style="text-align: center;max-width:30px">图标</th>
                            <th style="text-align: center;width: 30%;">店铺名</th>
                            <th style="text-align: center;">销售额(万元)</th>
                            <th style="text-align: center;">客单数</th>
                            <th style="text-align: center;">客单数环比增长</th>
                            <th style="text-align: center;">客单数同比增长</th>
                            <th style="text-align: center;">客单价</th>
                        </tr>
                        </thead>
                        <tbody id="shopTableBody">
                        </tbody>
                    </table>
                </div>
                </div>
                </div>
            </div>

        <#--产品-->
        <div class="row">
            <div class="col-md-12">
                <div class="widget">
                    <header class="widget-header">
                        <form class="form-inline" style="height:50px;padding-left:20px">
                            <label>附近店铺</label>
                            <select class="form-control" id="nearby_shops" title="" style="width: 330px;">
                            </select>
                        </form>
                    </header>
                    <div class="widget-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="widget">
                                    <div class="widget-body">
                                        <div id="compareplatform" style="overflow-y:scroll;height:465px">
                                        <#--<table id="compareplatformtable" class="table table-hover" style="text-align: left;height:265px">-->
                                            <table class="table" id="compareplatformtable" style="text-align: center;">
                                                <thead style="border-bottom: 3px solid #ba1b20">
                                                <tr>
                                                    <th>类型</th>
                                                    <th>产品名</th>
                                                <#--<th>图片</th>-->
                                                    <th>价格(元)</th>
                                                    <th>销售额(元)</th>
                                                    <th>销售量</th>
                                                    <th>推荐数</th>
                                                </tr>
                                                </thead>
                                                <tbody id="product_table_body">

                                                </tbody>
                                            </table>
                                        </div><!-- .widget-body -->
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <#--月度趋势-->
                            <div class="col-md-6 col-sm-12">
                                        <div class="widget">
                                            <header class="widget-header">
                                                <h4 class="widget-title" id="widget1">月度趋势
                                                    <button type="button" class="pull-right btn rounded btn-default" id="btn_sata">满意度
                                                    </button>&nbsp;
                                                    <button type="button" class="pull-right btn rounded btn-default"id="btn_sale">销售额
                                                    </button>&nbsp;
                                                    <button type="button" class="pull-right btn rounded btn-default button_active"id="btn_ta">客单数
                                                    </button>&nbsp;
                                                </h4>
                                            </header>
                                            <hr class="widget-separator">
                                            <div class="widget-body">
                                                <div id="satisfaction" style="height:300px">

                                                </div>
                                            </div>
                                        </div>
                            </div>
                            <#--词云图-->
                            <div class="col-md-6 col-sm-12">
                                    <div class="widget">
                                        <header class="widget-header">
                                            <h4 class="widget-title" id="widget5">词云图
                                                </button>&nbsp;
                                            </h4>
                                        </header>
                                        <hr class="widget-separator">
                                        <div class="widget-body" style="padding:0 0;height: 353px">
                                            <div class="row" style="padding:0px 10px;">
                                                <div class="col-md-6" style="padding:0 0">
                                                    <div id="word_cloud1" style="height: 343px;width:100%;">

                                                    </div>
                                                </div>
                                                <div class="col-md-6"  style="padding:0 0">
                                                    <div id="word_cloud2" style="height: 343px;width:100%;">

                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        </section><!-- #dash-content -->
    </div><!-- .wrap -->
    <!-- APP FOOTER -->


<#include "../static/footer.ftl" >

</main>
<!--========== END app main -->
<script src="/res/assets/js/bootstrap-datepicker.js"></script>
<script src="/res/assets/js/bootstrap-select.js"></script>
<script src="../../res/assets/js/bootstrap-table.js"></script>

<script type="text/javascript"
        src='http://webapi.amap.com/maps?v=1.4.3&key=9fa8c62b85a987698a515fbddee8efa7&&plugin=AMap.ToolBar'></script>
<script src="/res/assets/js/jquery.webui-popover.min.js"></script>
<script type="text/javascript" src='../res/assets/js/heatmap.js'></script>
<script type="text/javascript" src="/res/assets/js/jqcloud-1.0.4.min.js"></script>

<script>
    var CATE_SELECT = $("#cate_select");
    var BRAND_SELECT = $("#brand_select");
    var SHOP_SELECT = $("#shop_select");
    SHOP_SELECT.selectpicker({noneSelectedText: ""});
    var CITY_SELECT = $("#city_select");
    var CATE_BRAND;
    var SHOPS;//单店概览数据，
    var COMPSHOPS;//所有竞争店铺
    var COMPSHOPOVERVIEW;//各个竞争店铺的概览数据
    var SHOPID =${shopid}
    var CITIES = []
    var CITIES_SHOPS = [] //城市对应的店铺[[shop1,shop2],[]]
    var shop_colors={}//地图竞争店铺 颜色  ，用于表格显示
    $(document).ready(function () {
        //获取最新数据的月份
        getLatestMonth()
        init();
        window.onresize = function () {
            myChart1.resize();
        }
        var username = '${user_name}';
        $("#userName").html(username);
        $(".app-menu li").each(function () {
            $(this).removeAttr("class");
        });
        $(".app-menu li a").each(function () {
            $(this).removeAttr("style");
        });
        $("#menu_shop").attr("class", "active");
        $("#menu_shop a").attr("style", "color: #ba1b20");

        $("#nav_bar").append("<li>\n" +
                "                    <a class=\"page-title hidden-menubar-top hidden-float\" style='color: white'>/单店分析</a>\n" +
                "                </li>");

        $("#search").click(function () {
            if (CATE_SELECT.val() == null
                    || BRAND_SELECT.val() == null
                    || SHOP_SELECT.val() == null
                    || CITY_SELECT.val() == null) {
                alert("请选择查询条件！")
            } else {
                $("#nearby_shops").html("");
                search();
            }
        })
        $("#btn_sata").click(function () {
            getSatisfaction(3)
            $("#btn_sale").attr("class", "pull-right btn rounded btn-default");
            $("#btn_ta").attr("class", "pull-right btn rounded btn-default");
            $(this).attr("class", "pull-right btn rounded btn-default button_active");
        });
        $("#btn_sale").click(function () {
            getSatisfaction(2)
            $("#btn_sata").attr("class", "pull-right btn rounded btn-default");
            $("#btn_ta").attr("class", "pull-right btn rounded btn-default");
            $(this).attr("class", "pull-right btn rounded btn-default button_active");

        });
        $("#btn_ta").click(function () {
            getSatisfaction(1)
            $("#btn_sale").attr("class", "pull-right btn rounded btn-default");
            $("#btn_sata").attr("class", "pull-right btn rounded btn-default");
            $(this).attr("class", "pull-right btn rounded btn-default button_active");
        });

        function init() {
            if (SHOPID == "-1") {
                //获取店铺下拉框
                initShopSelect("汉堡", "肯德基", true, null, null, true)
                //获取店铺基本信息
                initShopInfo('上海肯德基宅急送顾村店', "肯德基")
                //获取店铺表格数据
                initShopTable('上海肯德基宅急送顾村店', "肯德基")
                //品类品牌下拉框初始化
                initSelect('汉堡', '肯德基')
            } else {
                var startMonth = $("#start_date").val().replace("-", "");
                var endMonth = $("#end_date").val().replace("-", "");
                //下拉框   根据店铺获取品类和品牌
                $.ajax({
                    type: "GET",
                    url: "/service/data/getStoreBrandList",
                    data: {
                        start_month: startMonth,
                        end_month: endMonth,
                        restaurantID: SHOPID
                    },
                    success: function (res) {
                        if (res.code === "suc") {
                            try {
                                var brandDefault = res.data;
                                var subCate = brandDefault.restaurantSubCategoryName
                                var brandName = brandDefault.brandName
                                var restaurantName = brandDefault.restaurantName
                                var city = brandDefault.city
                                //品类品牌下拉框初始化
                                initSelect(subCate, brandName)
                                //获取店铺下拉框
                                initShopSelect(subCate, brandName, true, restaurantName, city, true)
                                //获取店铺基本信息
                                initShopInfo(restaurantName, brandName)

                                //获取店铺表格数据
                                initShopTable(restaurantName, brandName)
                            } catch (e) {
                            }
                        }
                    }
                });
            }
        }

        function search() {
            //获取店铺基本信息
            initShopInfo(null, null)
            //获取店铺表格数据
            initShopTable(null, null)
            //词云图
            getWordCloud()
            getYoYMoM();
            getRatingTrend();
        }


        //词云图
        function getWordCloud(store,brand) {
            var endMonth = $("#end_date").val().replace("-", "");
            var start_date = $("#start_date").val().replace("-", "");
            var storeName = store==null?SHOP_SELECT.val():store;
            var brandName = brand==null?BRAND_SELECT.val():brand;
            $.ajax({
                type: "GET",
                url: "/service/data/getStoreKeyWord",
                data: {
                    end_month: endMonth,
                    storeName: storeName,
                    start_month: start_date,
                    brandName: brandName
                },
                success: function (res) {
                    if (res.code === "suc") {
                        var monthDatas = res.data;
                        var words1 = [];//情感类
                        var words2 = [];
                        var idx1=0
                        var idx2=0
                        monthDatas.forEach(function (value, index) {
                            var word = {}
                            word["text"] = value.keyword
                            word["weight"] = value.wordCount
                            if(value.emotion!=null&&value.emotion==1){
                                words1[idx1++] = word
                            }else {
                                words2[idx2++] = word
                            }
                        })
                        $("#word_cloud1").empty()
                        $("#word_cloud1").jQCloud(words1);
                        $("#word_cloud2").empty()
                        $("#word_cloud2").jQCloud(words2);
                    }
                }
            });
        }

        //品类品牌下拉框初始化
        function initSelect(defaultSub, defaultBrand) {
            $.ajax({
                type: "GET",
                url: "/service/data/getAllSubCategory",
                async: false,
                success: function (res) {
                    if (res.code === "suc") {
                        try {
                            CATE_BRAND = res.data;
                            CATE_SELECT.html("");
                            BRAND_SELECT.html("");
                            var tmpBrandList = CATE_BRAND[defaultSub];
                            tmpBrandList.forEach(function (value, index) {
                                BRAND_SELECT.append("<option value='" + value + "'>" + value + "</option>");
                            });
                            for (var value in CATE_BRAND) {
                                CATE_SELECT.append("<option value='" + value + "'>" + value + "</option>");
                            }
                            ;
                            CATE_SELECT.val(defaultSub);
                            BRAND_SELECT.val(defaultBrand);
                        } catch (e) {
                        }
                    }
                }
            });
        }

        //g获取店铺下拉框fla(获取词云图标记)
        function initShopSelect(subCatName, brandName, first, default_name, city, flag) {
            var startMonth = $("#start_date").val().replace("-", "");
            var endMonth = $("#end_date").val().replace("-", "");
            var subCatName = subCatName == null ? CATE_SELECT.val() : subCatName;
            var brandName = brandName == null ? BRAND_SELECT.val() : brandName;
            $.ajax({
                type: "GET",
                url: "/service/data/getStoreNameList",
                data: {
                    start_month: startMonth,
                    end_month: endMonth,
                    brandName: brandName,
                    subcat_name: subCatName
                },
                success: function (res) {
                    if (res.code === "suc") {
                        try {
                            var shops = res.data;
                            var idx = 0
                            //格式化
                            CITIES=[]
                            CITIES_SHOPS=[]
                            if(shops.length<=0){
                                // CITY_SELECT.empty()
                                SHOP_SELECT.empty()
                                SHOP_SELECT.selectpicker('refresh');
                                //店铺搜索下拉框样式
                                initShopSelectSytle()
                                alert("没有店铺信息！")
                                return
                            }
                            shops.forEach(function (value, index) {
                                var now_idx = CITIES.indexOf(value["city"]);
                                if (now_idx == -1) {
                                    CITIES[idx] = value["city"]
                                    CITIES_SHOPS[idx] = [value["restaurantName"]]
                                    idx++
                                } else {
                                    CITIES_SHOPS[now_idx].push(value["restaurantName"])
                                }
                            });
                            var shops_idx=CITIES.indexOf(city)
                            if(city!=null&&shops_idx==-1){
                                SHOP_SELECT.empty()
                                alert("该品牌在城市："+city+"不存在!")
                            }else {
                                CITY_SELECT.empty()
                                CITIES.forEach(function (value, index) {
                                    CITY_SELECT.append("<option value='" + value + "'>" + value + "</option>");
                                })
                                if (default_name != null) {//   /shop_with_shopid?shopid=334
                                    CITY_SELECT.val(city)
                                    var shops_idx = CITIES.indexOf(city)
                                    SHOP_SELECT.empty()
                                    CITIES_SHOPS[shops_idx].forEach(function (value, index) {
                                        SHOP_SELECT.append("<option value='" + value + "'>" + value + "</option>");
                                    })
                                    SHOP_SELECT.selectpicker('refresh');
                                    SHOP_SELECT.val(default_name);
                                } else if (first) {//   /shop
                                    CITY_SELECT.val("上海")
                                    var shops_idx = CITIES.indexOf("上海")
                                    SHOP_SELECT.empty()
                                    CITIES_SHOPS[shops_idx].forEach(function (value, index) {
                                        SHOP_SELECT.append("<option value='" + value + "'>" + value + "</option>");
                                    })
                                    SHOP_SELECT.val('上海肯德基宅急送顾村店');
                                    SHOP_SELECT.selectpicker('refresh');

                                } else {
                                    var shops_idx = CITIES.indexOf(city)
                                    CITY_SELECT.val(city)
                                    SHOP_SELECT.empty()
                                    CITIES_SHOPS[shops_idx].forEach(function (value, index) {
                                        SHOP_SELECT.append("<option value='" + value + "'>" + value + "</option>");
                                    })
                                    SHOP_SELECT.val(CITIES_SHOPS[shops_idx][0]);
                                    SHOP_SELECT.selectpicker('refresh');
                                }
                                //店铺搜索下拉框样式
                                initShopSelectSytle()
                                if (flag) {
                                    //获取店铺下拉框  之后才能调用下面3个
                                    //词云图
                                    getWordCloud()
                                    getYoYMoM();
                                    getRatingTrend();
                                }
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    }
                }
            });
        }

        CATE_SELECT.change(function () {
            SHOPID = "-1"
            BRAND_SELECT.html("");
            var nowCate = CATE_SELECT.val();
            var tmpBrandList = CATE_BRAND[nowCate];
            tmpBrandList.forEach(function (value, index) {
                BRAND_SELECT.append("<option value='" + value + "'>" + value + "</option>");
            });
            initShopSelect(CATE_SELECT.val(),BRAND_SELECT.val(),false,null,CITY_SELECT.val(),false)
        });
        BRAND_SELECT.change(function () {
            SHOPID = "-1"
            //获取店铺下拉框
            initShopSelect(CATE_SELECT.val(),BRAND_SELECT.val(),false,null,CITY_SELECT.val(),false)
        });
        SHOP_SELECT.change(function () {
            SHOPID = "-1"
        });
        CITY_SELECT.change(function () {
            SHOPID = "-1"
            var shops_idx = CITIES.indexOf($(this).val())
            SHOP_SELECT.empty()
            CITIES_SHOPS[shops_idx].forEach(function (value, index) {
                SHOP_SELECT.append("<option value='" + value + "'>" + value + "</option>");
            })
            SHOP_SELECT.selectpicker('refresh');
            SHOP_SELECT.val(CITIES_SHOPS[shops_idx][0]);
            //店铺搜索下拉框样式
            initShopSelectSytle()
        });

        //店铺搜索下拉框样式
        function initShopSelectSytle() {
            $(".btn-group").css({
                "min-width": "150px",
                "width": "80%"
            })
        }

        //获取最新数据的月份
        function getLatestMonth() {
            $('.datepicker').datepicker({
                format: 'yyyy-mm',
                startView: 1,
                todayHighlight: true,
                maxViewMode: 'years',
                minViewMode: 'months',
                endDate: new Date().Format('yyyyMM')
            });

            $.ajax({
                type: "GET",
                url: "/service/view/get_latest_month",
                async: false,
                success: function (res) {
                    if (res.code === "suc") {
                        try {
                            defaultMonth = res.data.yearMonth.toString().substring(0, 4)
                                    + "-" + res.data.yearMonth.toString().substring(4, 6);
                            $('.datepicker').datepicker('update', defaultMonth);
                            $("#start_datapicker").datepicker('update', res.data.yearMonth.toString().substring(0, 4) + "-01");
                        } catch (e) {
                        }

                    }
                }
            });
        }

        //获取店铺基本信息
        function initShopInfo(restaurant, brandName) {
            var startMonth = $("#start_date").val().replace("-", "");
            var endMonth = $("#end_date").val().replace("-", "");
            var restaurant = restaurant == null ? SHOP_SELECT.val() : restaurant;
            var brandName = brandName == null ? BRAND_SELECT.val() : brandName;
            $.ajax({
                type: "GET",
                url: "/service/data/getStoreOverviewResult",
                data: {
                    start_month: startMonth,
                    end_month: endMonth,
                    brand_name: brandName,
                    restaurant: restaurant
                },
                success: function (res) {
                    if (res.code === "suc") {
                        try {
                            //---------------------单店概览数据，---------------------
                            SHOPS = res.data.shopOverView;
                            var html = "<table><tr><td style='min-width: 80px;'><h4>店铺名：</h4></td><td><h4>" + SHOPS.restaurantName + "</h4></td></tr>" +
                                    "<tr><td><h4>地址：</h4></td><td><h4>" + SHOPS.storeAddress + "</h4></td></tr>";
                                    //+"<tr><td><h4>电话：</h4></td></tr>"
                            $("#shop_info").empty()
                            $("#shop_info").append(html)
                            //---------------------所有竞争店铺---------------------
                            COMPSHOPS = res.data.compShops;
                            var long_las=[]
                            COMPSHOPS.forEach(function(val,idx){
                                var long_la=[]
                                var long=val.competitorLongitude
                                var la=val.competitorLatitude
                                var name = val.competitorRestaurantName;
                                var adress = val.competitorAddress;
                                if(long!=null && la!=null ){
                                    long_la.push(long)
                                    long_la.push(la)
                                    long_la.push(name)
                                    long_la.push(adress)
                                    long_las.push(long_la)
                                }else{
                                    console.info(val['competitorRestaurantName']+"经纬度不完整")
                                }

                            })
                            //---------------------各个竞争店铺的概览数据---------------------
                            initShopMap(SHOPS.longitude, SHOPS.latitude,long_las);
                            getShopOverview();
                            getcomtableinfo(restaurant, brandName);
                            //getnearby_shops();
                            //各个竞争店铺的概览数据
                            //initCompShop()
                        } catch (e) {
                        }
                    }
                }
            });
        }
        function getcomtableinfo(restaurant, brandName) {
            var startMonth = $("#start_date").val().replace("-", "");
            var endMonth = $("#end_date").val().replace("-", "");
            var restaurant = restaurant == null ? SHOP_SELECT.val() : restaurant;
            var brandName = brandName == null ? BRAND_SELECT.val() : brandName;
            $("#shopTableBody").html("数据加载中.....");
            $.ajax({
                type: "GET",
                url: "/service/data/getcomstoreinforesult",
                data: {
                    start_month: startMonth,
                    end_month: endMonth,
                    brand_name: brandName,
                    restaurant: restaurant
                },
                success: function (res) {
                    if (res.code === "suc") {
                        COMPSHOPOVERVIEW = res.data;
                        getnearby_shops();
                        //各个竞争店铺的概览数据
                        initCompShop();
                    }
                }
            });
        }
        //店铺地图  long_lats格式：[[longitude,latitude],[],]
        function initShopMap(longitude, latitude,long_lats) {
            shop_colors={}
            map = new AMap.Map('mapDiv', {
                resizeEnable: true,
                //zoom: 15,
                zooms: [12, 17],
                //根据传入的经纬度确定地图中心
                center: [longitude, latitude],
                dragEnable: true,
                zoomEnable: true
            });
            var color = "#f63843";
            var marker_icon1=getMakerIcon(21,21,color);
            var marker = new AMap.Marker({
                // content:marker_icon1,
                icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
                position: [longitude, latitude],
                visible: true
            });
            var infoWindow = new AMap.InfoWindow({
                closeWhenClickMap: true,
                isCustom: true,
                offset: new AMap.Pixel(0, -30)
            });
            marker.on('mouseover',function (e) {
                infoWindow.setContent("<div class='widget' " +
                        "style='opacity: 0.86;background-color: #565656'>" +
                        "<div class='widget-body'>" +
                        "<p class='text-muted' style='color: white'>店铺名：" + SHOPS.restaurantName + "</p>\n" +
                        "<p class='text-muted' style='color: white'>店铺地址：" + SHOPS.storeAddress + "</p>\n" +
                        "</div></div>");
                infoWindow.open(map, e.target.getPosition());
            });
            var markers=[];
            long_lats.forEach(function(val,idx){
                var color =  getRandomColor('f63843');
                shop_colors[val[2]]=color;
                var marker_icon=getMakerIcon(21,21,color);
                var marker1 = new AMap.Marker({
                    // icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                    content: marker_icon,
                    position: [val[0], val[1]],
                    visible: true
                });
                marker1.on('mouseover',function (e) {
                    infoWindow.setContent("<div class='widget' " +
                            "style='opacity: 0.86;background-color: #565656'>" +
                            "<div class='widget-body'>" +
                            "<p class='text-muted' style='color: white'>店铺名：" + val[2] + "</p>\n" +
                            "<p class='text-muted' style='color: white'>店铺地址：" + val[3] + "</p>\n" +
                            "</div></div>");
                    infoWindow.open(map, e.target.getPosition());
                });
                markers.push(marker1);
            })
            markers.push(marker)
            map.add(markers);
            map.setFitView();
        }
        //店铺商品详情-店铺下拉框
        function getnearby_shops() {
            var html;
            html = "<option value=\""+SHOPS.brandName+"\">"+SHOPS.restaurantName+"</option>";
            for(var val in COMPSHOPOVERVIEW) {
                html = html + "<option value=\""+COMPSHOPOVERVIEW[val].sales.brandName+"\">"+val+"</option>";
            }
            $("#nearby_shops").html(html);
        }
        $("#nearby_shops").change(function () {
            var restaurantName = $("#nearby_shops  option:selected").text();
            var brandName = $("#nearby_shops  option:selected").val();
            initShopTable(restaurantName,brandName);
            getRatingTrend(restaurantName,brandName)
            getWordCloud(restaurantName,brandName);
        });
        //获取店铺表格数据
        function initShopTable(restaurant, brandName) {
            var startMonth = $("#start_date").val().replace("-", "");
            var endMonth = $("#end_date").val().replace("-", "");
            var restaurant = restaurant == null ? SHOP_SELECT.val() : restaurant;
            var brandName = brandName == null ? BRAND_SELECT.val() : brandName;
            $.ajax({
                type: "GET",
                url: "/service/data/getStoreOverviewResultbyProduct",
                data: {
                    start_month: startMonth,
                    end_month: endMonth,
                    brandName: brandName,
                    restaurantName: restaurant
                },
                success: function (res) {
                    if (res.code === "suc") {
                        try {
                            var shops = res.data;
                            var html = ""
                            if (shops.length > 0) {
                                var productType = {}
                                shops.forEach(function (value, index) {
                                    var type = productType[value.productType]
                                    if (type != undefined) {
                                        productType[value.productType] = productType[value.productType] + 1
                                    } else {
                                        productType[value.productType] = 1
                                    }
                                })
                                //shops数据需要按产品类型排序
                                var fisrt = "-1"
                                shops.forEach(function (value, index) {
                                    var price = formatNum(new Number(value.adjustedProductPrice).toFixed(decimals_num))//价格(元)
                                    var productsales = formatNum(new Number(value.productsales).toFixed(decimals_num))
                                    var productTC = formatNum(new Number(value.productTC).toFixed(decimals_num))
                                    if (fisrt == value.productType) {
                                        html = html + "<tr>" +
                                                "  <td>" + value.productName + "</td>" +
                                                "  <td>" + price + "</td>" +//价格(元)
                                                "  <td>" + productsales + "</td>" +
                                                "  <td>" + productTC + "</td>" +
                                                "  <td></td>" +//推荐数
                                                "</tr>"
                                    } else {
                                        fisrt = value.productType
                                        var nums = productType[value.productType]
                                        html = html + "<tr>" +
                                                "  <td rowspan='" + nums + "'style='color:#cf3138;font-weight:bold;'>" + value.productType + "</td>" +
                                                "  <td>" + value.productName + "</td>" +
                                                "  <td>" + price + "</td>" +//价格(元)
                                                "  <td>" + productsales + "</td>" +
                                                "  <td>" + productTC + "</td>" +
                                                "  <td></td>" +//推荐数
                                                "</tr>"
                                    }
                                })
                            } else {
                                html = "<tr><td colspan='6'><span>没有该店铺的数据！</span></td></tr>"
                            }
                            $("#product_table_body").empty()
                            $("#product_table_body").append(html)
                            if (shops.length < 6) {
                                $('#compareplatform').attr("st." +
                                        "3yle", "")
                                $('#compareplatformtable').attr("style", "")
                            } else {
                                $('#compareplatform').attr("style", "overflow-y:scroll;height:465px")
                            }
                            $('#compareplatformtable thead tr th').css({
                                "text-align": "center",
                            })


                        } catch (e) {
                        }

                    }
                }
            });
        }

    });
    //随机颜色
    function getRandomColor(main_shop_color){//主店铺之外的颜色

        var color=(function(color){
            return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)])
            && (color.length == 6) ?  color : arguments.callee(color);
        })('');
        while(isSimilarColor(color,main_shop_color,10)){
            color=(function(color){
                return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)])
                && (color.length == 6) ?  color : arguments.callee(color);
            })('');
        }
        return "#"+color;

    }
    function getMakerIcon(width,height,color){
        return  "<div style='display:inline-block;width: "+width+"px;\n" +
                "        height: "+height+"px;\n" +
                "        border-radius: 80% 0 55% 50% / 55% 0 80% 50%;\n" +
                "        transform: rotate(135deg);\n" +
                "        background-color: " + color + ";\n" +
                "        border-color: #888886;\n" +
                "        border-style: solid;\n" +
                "        border-width: 2px;'></div>";
    }

    //判断两种颜色值是否为相似颜色
    function isSimilarColor(sHexColorA,sHexColorB,nOffset){
        this.offsetNum=Math.abs(nOffset);
        this.offsetNum>255?this.offsetNum=this.offsetNum-256:"";
        var arrNumA=[parseInt(sHexColorA.substring(0,2),16),
            parseInt(sHexColorA.substring(2,4),16),
            parseInt(sHexColorA.substring(4,6),16)];
        var arrNumB=[parseInt(sHexColorB.substring(0,2),16),
            parseInt(sHexColorB.substring(2,4),16),
            parseInt(sHexColorB.substring(4,6),16)];
        for (var i=0;i<arrNumA.length;i++){
            if(Math.abs(arrNumA[i]-arrNumB[i])>this.offsetNum){
                return false;
            };
        }
        return true;
    }

    //竞争店铺展示
    function getShopOverview() {
        $("#sales").html(formatNum(SHOPS.storeValues.toFixed(decimals_num)));
        $("#tc").html(formatNum(SHOPS.storeTC.toFixed(decimals_num)));
        $("#ta").html(formatNum(SHOPS.storeTA.toFixed(decimals_num)));
    }
    //绿色向上箭头、红色向下箭头
    var up_arrow = "&nbsp;%&nbsp;<i class=\"glyphicon glyphicon-arrow-up\" style=\"color: #21dd21\"></i>";
    var down_arrow = "&nbsp;%&nbsp;<i class=\"glyphicon glyphicon-arrow-down\" style=\"color: #ff0000\"></i>";
    //各个竞争店铺的概览数据
    function initCompShop() {
        $("#shopTableBody").html("");
        //销毁表格，便于之后重新生成数据
        $('#shopTable').DataTable().destroy();
        var html2= "";
        if(JSON.stringify(COMPSHOPOVERVIEW) == "{}"){
            $("#table_shop").hide();
        }else{
            for(var value in COMPSHOPOVERVIEW) {
                //销售额
                var sales = "";
                //客单数
                var guests = "";
                //客单数环比增长
                var guests_ta = "";
                //客单数同比增长
                var guests_tc = "";
                //客单价
                var guests_sale = "";
                $("#shopTableBody").html("");
                //销毁表格，便于之后重新生成数据
                $('#shopTable').DataTable().destroy();
                    sales = formatNum(convBill(COMPSHOPOVERVIEW[value].sales.storeValues, index_decimals_num).num);
                    guests = formatNum(new Number(COMPSHOPOVERVIEW[value].sales.storeTC).toFixed(decimals_num));
                    guests_tc = (COMPSHOPOVERVIEW[value].yoy.storeTCYoY * 100).toFixed(decimals_num)+"%";
                    guests_ta = (COMPSHOPOVERVIEW[value].yoy.storeTCMoM * 100).toFixed(decimals_num)+"%";
                    guests_sale = formatNum(new Number(COMPSHOPOVERVIEW[value].sales.storeTA).toFixed(decimals_num));
                var shop_color=shop_colors[value]
                var resName="",shopColorTd="";
                if(shop_color!=null){
                    resName="<span style='padding-right: 10px'>"+value+"</span>";
                    shopColorTd=getMakerIcon(12,12,shop_color);
                }else{
                    resName=restaurantName
                }
                html2 = html2 + ("<tr>" +
                        "<td align='center'>"+shopColorTd+"</td>"+
                        "<td align='center' style='color:#cf3138;font-weight:bold'> " +resName +"</td>" +
                        "<td align='center'>" + sales + "</td>" +
                        "<td align='center'>" + guests + "</td>" +
                        "<td align='center'>" + guests_tc + "</td>" +
                        "<td align='center'>" + guests_ta + "</td>" +
                        "<td align='center'>" + guests_sale + "</td>" +
                        "</tr>");
                $("#shopTableBody").html(html2);
                $("#shopTableBody")
                var table = $('#shopTable').DataTable({
                    //搜索框
                    "searching": false,
                    //是否排序
                    "bSort": true,
                    //是否显示每页显示数据大小
                    "bLengthChange": false,
                    //隐藏表格信息
                    "bInfo": false,
                    "aoColumnDefs": [{"bSortable": false, "aTargets": [0]}],
                    "aaSorting": [[1, "desc"]]
                });
                $('#shopTable_filter > label > input').on('keyup', function () {
                    table.columns(0).search(this.value).draw();
                });
                $('#shopTableBody tr.odd').css({
                    'background-color':'#fff3f5'
                })
                $('#shopTable').on( 'order.dt',  function () {
                    $('.table-striped > tbody > tr').css({
                        'background-color':'white'
                    });
                    $('.table-striped > tbody > tr:nth-of-type(odd)').css({
                        'background-color':'#fff3f5'
                    });
                })
            }
            $("#table_shop").show();
        }
        /*
        $("#shopTable thead tr").css({
            //"background": "#ba1a20",
            //"color": "#fff"
        })*/
        //设置表格的列 无边框initTableStyle
        $('#shopTable thead').css({
            //"background": "#ba1b20",
            //"color": "#ffffff"
            "border-bottom": "3px solid #ba1b20"
        })
        $('#shopTable').css({
            "width": "100%",
        })
        $("#default-datatable thead tr").css({
            "background": "#ba1a20",
            "color": "#fff"
        })
        $('#shopTable tr.odd').css({
            'background-color':'#fff3f5'
        })
    }


    function getYoYMoM() {
        var start_month = $("#start_date").val();
        var end_month = $("#end_date").val();
        var brand_name = $("#brand_select").val();
        var restaurant = $("#shop_select").val();
        $.get("/service/data/getStoreOverviewResultRate",
                {
                    start_month: start_month,
                    end_month: end_month,
                    brand_name: brand_name,
                    restaurant: restaurant
                }, function (data) {
                    if (data.code === 'suc') {
                        var realData = data.data;
                        if (realData.storeValuesMoM >= 0) {
                            $("#sales_mom").html("环比增长：" + (realData.storeValuesMoM * 100).toFixed(decimals_num) + up_arrow);
                        } else {
                            $("#sales_mom").html("环比增长：" + (realData.storeValuesMoM * 100).toFixed(decimals_num) + down_arrow);
                        }
                        if (realData.storeTCMoM >= 0) {
                            $("#tc_mom").html("环比增长：" + (realData.storeTCMoM * 100).toFixed(decimals_num) + up_arrow);
                        } else {
                            $("#tc_mom").html("环比增长：" + (realData.storeTCMoM * 100).toFixed(decimals_num) + down_arrow);
                        }
                        if (realData.storeTAMoM >= 0) {
                            $("#ta_mom").html("环比增长：" + (realData.storeTAMoM * 100).toFixed(decimals_num) + up_arrow);
                        } else {
                            $("#ta_mom").html("环比增长：" + (realData.storeTAMoM * 100).toFixed(decimals_num) + down_arrow);
                        }
                        //同比
                        if (realData.storeValuesYoY >= 0) {
                            $("#sales_yoy").html("同比增长：" + (realData.storeValuesYoY * 100).toFixed(decimals_num) + up_arrow);
                        } else {
                            $("#sales_yoy").html("同比增长：" + (realData.storeValuesYoY * 100).toFixed(decimals_num) + down_arrow);
                        }
                        if (realData.storeTCYoY >= 0) {
                            $("#tc_yoy").html("同比增长：" + (realData.storeTCYoY * 100).toFixed(decimals_num) + up_arrow);
                        } else {
                            $("#tc_yoy").html("同比增长：" + (realData.storeTCYoY * 100).toFixed(decimals_num) + down_arrow);
                        }
                        if (realData.storeTAYoY >= 0) {
                            $("#ta_yoy").html("同比增长：" + (realData.storeTAYoY * 100).toFixed(decimals_num) + up_arrow);
                        } else {
                            $("#ta_yoy").html("同比增长：" + (realData.storeTAYoY * 100).toFixed(decimals_num) + down_arrow);
                        }
                    }
                });
    }

    var TREND;

    function getRatingTrend(shop_name,brand_name) {
        var end_month = $("#end_date").val();
        var brand_name = brand_name==null?$("#brand_select").val():brand_name;
        var restaurant = shop_name==null?$("#shop_select").val():shop_name;
        $.get("/service/data/getStoreMonthlyRatingTrend",
                {
                    end_month: end_month,
                    brand_name: brand_name,
                    restaurant: restaurant
                }, function (data) {
                    if (data.code == 'suc') {
                        TREND = data.data;
                        getSatisfaction(1);
                    }
                });
    }

    //满意度趋势
    function getSatisfaction(idx) {
        if(TREND!=null) {
            //若未定义，则新建
            if (typeof echarts.getInstanceByDom(document.getElementById("satisfaction")) === 'undefined') {
                myChart1 = echarts.init(document.getElementById("satisfaction"))
            }
            var month = [], rating = [], yname = '';
            for (var i = 0; i < TREND.length; i++) {
                month[i] = TREND[i]["yearmonth"];
                switch (idx) {
                    case 1: //客单数
                        rating[i] = parseInt(new Number(TREND[i]["storeTC"]).toFixed(decimals_num));
                        yname = '客单数(笔)'
                        break;
                    case 2: //销售额
                        rating[i] = parseInt(new Number(TREND[i]["storeValues"]).toFixed(decimals_num));
                        yname = '销售额(元)'
                        break;
                    case 3: //满意度
                        rating[i] = parseInt(new Number(TREND[i]["storeRating"]).toFixed(decimals_num));
                        yname = '满意度(%)'
                        break;
                }

            }
            var option = {
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'category',
                    data: month,
                    name: '月份'
                },
                yAxis: {
                    splitLine:{show: false},
                    min:function(value) {
                        return parseInt(value.min*0.8);
                    },
                    max: function(value) {
                        if(yname == '满意度(%)'){
                            return 100;
                        }
                        return parseInt(value.max*1.2);
                    },
                    type: 'value',
                    name: yname
                },
                series: [{
                    data: rating,
                    type: 'line'
                }]
            };
            myChart1.clear();
            myChart1.setOption(option);
        }
    }

</script>
</body>
</html>